<%@ page contentType="text/html;charset=UTF-8" %>
<script>
$(document).ready(function() {
    $('#date').datetimepicker({
        format: "YYYY-MM-DD"
    });
	$('#transportPlanningTable').bootstrapTable({
		 
		  //请求方法
               method: 'get',
        height:550,
               //类型json
               dataType: "json",
               //显示刷新按钮
               showRefresh: true,
               //显示切换手机试图按钮
               showToggle: true,
               //显示 内容列下拉框
    	       showColumns: true,
    	       //显示到处按钮
    	       showExport: true,
    	       //显示切换分页按钮
    	       showPaginationSwitch: true,
    	       //显示详情按钮
    	       detailView: true,
    	       	//显示详细内容函数
	           detailFormatter: "detailFormatter",
    	       //最低显示2行
    	       minimumCountColumns: 2,
               //是否显示行间隔色
               striped: true,
               //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）     
               cache: false,    
               //是否显示分页（*）  
               pagination: true,   
                //排序方式 
               sortOrder: "asc",  
               //初始化加载第一页，默认第一页
               pageNumber:1,   
               //每页的记录行数（*）   
               pageSize: 10,  
               //可供选择的每页的行数（*）    
               pageList: [10, 25, 50, 100],
               //这个接口需要处理bootstrap table传递的固定参数,并返回特定格式的json数据  
               url: "${ctx}/tms/transportPlanning/data",
               //默认值为 'limit',传给服务端的参数为：limit, offset, search, sort, order Else
               //queryParamsType:'',   
               ////查询参数,每次调用是会带上这个参数，可自定义                         
               queryParams : function(params) {
               	var searchParam = $("#searchForm").serializeJSON();
               	searchParam.pageNo = params.limit === undefined? "1" :params.offset/params.limit+1;
               	searchParam.pageSize = params.limit === undefined? -1 : params.limit;
               	searchParam.orderBy = params.sort === undefined? "" : params.sort+ " "+  params.order;
                   return searchParam;
               },
               //分页方式：client客户端分页，server服务端分页（*）
               sidePagination: "server",
               contextMenuTrigger:"right",//pc端 按右键弹出菜单
               contextMenuTriggerMobile:"press",//手机端 弹出菜单，click：单击， press：长按。
               contextMenu: '#context-menu',
               onContextMenuItem: function(row, $el){
                   if($el.data("item") == "edit"){
                   	edit(row.id);
                   } else if($el.data("item") == "delete"){
                        jp.confirm('确认要删除该委托单记录吗？', function(){
                       	jp.loading();
                       	jp.get("${ctx}/tms/transportPlanning/delete?id="+row.id, function(data){
                   	  		if(data.success){
                   	  			$('#transportPlanningTable').bootstrapTable('refresh');
                   	  			jp.success(data.msg);
                   	  		}else{
                   	  			jp.error(data.msg);
                   	  		}
                   	  	})
                   	   
                   	});
                      
                   } 
               },
              
               onClickRow: function(row, $el){
               },
        columns: [{
            checkbox: true

        },{
            field: 'status',
            title: '委托单状态',
            sortable: true

        },
            {
                field: 'planStatus',
                title: '计划状态',
                sortable: true

            }
            ,{
                field: 'entrustNumber',
                title: '委托单号',
                sortable: true
                ,formatter:function(value, row , index){
                    return "<a href='javascript:edit(\""+row.id+"\")'>"+value+"</a>";
                }

            } ,{
                field: 'shipmentNumbers',
                title: '装运单号',
                sortable: true

            } ,{
                field: 'date',
                title: '下单日期',
                sortable: true
                ,formatter:function(value, row , index){
                    return value.toString().substring(0,16)
                }
            } ,{
                field: 'deliveryTime',
                title: '要求发货时间',
                sortable: true
                ,formatter:function(value, row , index){
                    return value.toString().substring(0,16)
                }
            } ,{
                field: 'arrivalTime',
                title: '要求到货时间',
                sortable: true

            }
            ,{
                field: 'weight',
                title: '总重量',
                sortable: true

            },{
                field: 'wf',
                title: '未发重量',
                sortable: true

            },{
                field: 'contractDistance',
                title: '起运地',
                sortable: true

            }
            ,{
                field: 'arriveProvince',
                title: '到站省',
                sortable: true

            }
            ,{
                field: 'arriveCity',
                title: '到站地城市',
                sortable: true

            },{
                field: 'site',
                title: '收货详细地址',
                sortable: true

            }  ,{
                field: 'khyq',
                title: '客户特殊需求',
                sortable: true,


            } ,{
                field: 'unitName',
                title: '收货单位名称',
                sortable: true

            } ,{
                field: 'unitConfirmor',
                title: '收货单位确认人',
                sortable: true

            }
            ,{
                field: 'phone',
                title: '确认人电话',
                sortable: true

            }


            ,{
                field: 'type',
                title: '订单类型',
                sortable: true

            }




            ,{
                field: 'distance',
                title: '合同里程',
                sortable: true

            }
            ,{
                field: 'transitLines',
                title: '运输线路',
                sortable: true

            }

            ,{
                field: 'projectName',
                title: '项目名称',
                sortable: true

            }

            ,{
                field: 'transportMode',
                title: '运输方式',
                sortable: true

            }
            ,{
                field: 'clearingMode',
                title: '结算方式',
                sortable: true

            }
            ,{
                field: 'clearingType',
                title: '结算类型',
                sortable: true

            }




            ,{
                field: 'remarks',
                title: '备注信息',
                sortable: true

            }
        ]

    });
		
		  
	  if(navigator.userAgent.match(/(iPhone|iPod|Android|ios)/i)){//如果是移动端

		 
		  $('#transportPlanningTable').bootstrapTable("toggleView");
		}
	  
	  $('#transportPlanningTable').on('check.bs.table uncheck.bs.table load-success.bs.table ' +
                'check-all.bs.table uncheck-all.bs.table', function () {
            $('#add').prop('disabled',  $('#transportPlanningTable').bootstrapTable('getSelections').length!=1);
            $('#edit').prop('disabled', $('#transportPlanningTable').bootstrapTable('getSelections').length!=1);
           $('#del').prop('disabled', $('#transportPlanningTable').bootstrapTable('getSelections').length!=1);
          $('#qx').prop('disabled', $('#transportPlanningTable').bootstrapTable('getSelections').length!=1);
          $('#kj').prop('disabled', $('#transportPlanningTable').bootstrapTable('getSelections').length!=1);

          $('#dayin').prop('disabled', $('#transportPlanningTable').bootstrapTable('getSelections').length!=1);
          $('#cd').prop('disabled', $('#transportPlanningTable').bootstrapTable('getSelections').length!=1);

        });
		  
		$("#btnImport").click(function(){
			jp.open({
			    type: 1, 
			    area: [500, 300],
			    title:"导入数据",
			    content:$("#importBox").html() ,
			    btn: ['下载模板','确定', '关闭'],
				    btn1: function(index, layero){
					  window.location='${ctx}/tms/transportPlanning/import/template';
				  },
			    btn2: function(index, layero){
				        var inputForm =top.$("#importForm");
				        var top_iframe = top.getActiveTab().attr("name");//获取当前active的tab的iframe 
				        inputForm.attr("target",top_iframe);//表单提交成功后，从服务器返回的url在当前tab中展示
				        inputForm.onsubmit = function(){
				        	jp.loading('  正在导入，请稍等...');
				        }
				        inputForm.submit();
					    jp.close(index);
				  },
				 
				  btn3: function(index){ 
					  jp.close(index);
	    	       }
			}); 
		});
		    
	  $("#search").click("click", function() {// 绑定查询按扭
		  $('#transportPlanningTable').bootstrapTable('refresh');
		});
	 
	 $("#reset").click("click", function() {// 绑定查询按扭
		  $("#searchForm  input").val("");
		  $("#searchForm  select").val("");
		   $("#searchForm  .select-item").html("");
		  $('#transportPlanningTable').bootstrapTable('refresh');
		});
		
		
	});
		
  function getIdSelections() {
        return $.map($("#transportPlanningTable").bootstrapTable('getSelections'), function (row) {
            return row.id
        });
    }
function getstatusSelections() {
    return $.map($("#transportPlanningTable").bootstrapTable('getSelections'), function (row) {
        return row.status
    });
}
function getplanSelections() {
    return $.map($("#transportPlanningTable").bootstrapTable('getSelections'), function (row) {
        return row.planStatus
    });
}
  

function cd() {
      var s=getplanSelections();
      if(s!="部分计划"){
          return;
      }
    jp.confirm('确认要拆单吗？', function(){
        $.ajax({
            url:'${ctx}/tms/transportPlanning/cd?id='+getIdSelections(),
            success:function (data) {
              jp.success("拆单成功");
                    $('#transportPlanningTable').bootstrapTable('refresh');}


        })
    })
    
}
  function qxpz() {
      jp.confirm('确认要取消配载吗？', function(){
          $.ajax({
              url:'${ctx}/tms/tmsWaybill/qxpz?i='+getIdSelections(),
              success:function (data) {
              	if(data=="false"){
                    jp.error("库房已经出库，请联系库房恢复原始库存");
				}else if(data=="ht"){
                    jp.error("已生成合同不能取消配载，请先取消合同");
                }else{jp.success("取消配载成功");
                    $('#transportPlanningTable').bootstrapTable('refresh');}

              }
          })
	  })

  }
  function cjpz(){
  	var id = getIdSelections();
  	if(id==null||id==""){
        jp.error("请至少选择一条！");
  		return;
	}
	var status=getstatusSelections();
  	var plan=getplanSelections();
  	if(plan!="计划完成"){
	  jp.openDialog('创建配载', "${ctx}/tms/tmsWaybill/form1?i="+id,'1200px', '1000px', $('#transportPlanningTable'));}
  }
  // function zctx() {
  //     var id = getIdSelections();
  //     if(id==null||id==""){
  //         alert("请至少选择一条！");
  //         return;
  //     }
  //     var status=getstatusSelections();
  //     var plan=getplanSelections();
  //     if((status=="已配载")&&(plan=="计划完成"||plan=="部分计划")){
  //         jp.openDialog('装车填写', "${ctx}/tms/tmsWaybill/form2?i="+id,'1200px', '1200px', $('#transportPlanningTable'));}
  // }
  function ckd() {
       var plan=getplanSelections();
       if(plan=="计划完成"){
		   $.ajax({
			   url:'${ctx}/tms/tmsWaybill/ckd?i='+getIdSelections(),
			   success:function (data) {
                   jp.success("生成出库单成功");
               }
		   })

  }}
function kj() {

    jp.confirm('确认要进行快速配载装车吗？', function(){
    jp.openDialog('快速配载装车', "${ctx}/tms/tmsWaybill/form3?i="+getIdSelections(),'1200px', '1000px', $('#transportPlanningTable'));

    })

}
  function edit(id){//没有权限时，不显示确定按钮
  	  if(id == undefined){
			id = getIdSelections();
		}
	   <shiro:hasPermission name="tms:transportPlanning:edit">
	  jp.openDialogView('查看运输计划', "${ctx}/tms/transportPlanning/form?id=" + id,'1200px', '1200px', $('#transportPlanningTable'));
	   </shiro:hasPermission>
	  <shiro:lacksPermission name="tms:transportPlanning:edit">
	  jp.openDialogView('查看委托单', "${ctx}/tms/transportPlanning/form?id=" + id,'1000px', '800px', $('#transportPlanningTable'));
	  </shiro:lacksPermission>
  }





  function detailFormatter(index, row) {
	  var htmltpl =  $("#transportPlanningChildrenTpl").html().replace(/(\/\/\<!\-\-)|(\/\/\-\->)/g,"");
	  var html = Mustache.render(htmltpl, {
			idx:row.id
		});
	  $.get("${ctx}/tms/transportPlanning/detail?id="+row.id, function(transportPlanning){
    	var transportPlanningChild1RowIdx = 0, transportPlanningChild1Tpl = $("#transportPlanningChild1Tpl").html().replace(/(\/\/\<!\-\-)|(\/\/\-\->)/g,"");
		var data1 =  transportPlanning.materialInformationsList;
		for (var i=0; i<data1.length; i++){
			addRow('#transportPlanningChild-'+row.id+'-1-List', transportPlanningChild1RowIdx, transportPlanningChild1Tpl, data1[i]);
			transportPlanningChild1RowIdx = transportPlanningChild1RowIdx + 1;
		}

    	var transportPlanningChild2RowIdx = 0, transportPlanningChild2Tpl = $("#transportPlanningChild2Tpl").html().replace(/(\/\/\<!\-\-)|(\/\/\-\->)/g,"");
		var data2 =  transportPlanning.additionalChargesList;
		for (var i=0; i<data2.length; i++){
			addRow('#transportPlanningChild-'+row.id+'-2-List', transportPlanningChild2RowIdx, transportPlanningChild2Tpl, data2[i]);
			transportPlanningChild2RowIdx = transportPlanningChild2RowIdx + 1;
		}


      })

        return html;
    }

	function addRow(list, idx, tpl, row){
		$(list).append(Mustache.render(tpl, {
			idx: idx, delBtn: true, row: row
		}));
	}

</script>
<script type="text/template" id="transportPlanningChildrenTpl">
//<!--
	<div class="tabs-container">
		<ul class="nav nav-tabs">
				<li class="active"><a data-toggle="tab" href="#tab-{{idx}}-1" aria-expanded="true">物料信息</a></li>

		</ul>
		<div class="tab-content">
				 <div id="tab-{{idx}}-2" class="tab-pane fade ">
						<table class="ani table">
						<thead>
							<tr>
								<th>收支类型</th>
								<th>金额</th>
								<th>数量</th>
								<th>单价</th>
								<th>备注信息</th>
							</tr>
						</thead>
						<tbody id="transportPlanningChild-{{idx}}-2-List">
						</tbody>
					</table>
				</div>
				<div id="tab-{{idx}}-1" class="tab-pane fade in active">
					<table class="ani table">
						<thead>
							<tr>
								<th>提货单号</th>
								<th>物料名称</th>
								<th>物料编码</th>
								<th>物料规格</th>
								<th>物料类型</th>
								<th>计划量</th>
								<th>装车量</th>
								<th>毛重(吨)</th>
								<th>体积(M3)</th>
								<th>提货仓库</th>
								<th>备注信息</th>
							</tr>
						</thead>
						<tbody id="transportPlanningChild-{{idx}}-1-List">
						</tbody>
					</table>
				</div>
		</div>//-->
	</script>
	<script type="text/template" id="transportPlanningChild2Tpl">//<!--
				<tr>
					<td>
						{{row.balanceType}}
					</td>
					<td>
						{{row.money}}
					</td>
					<td>
						{{row.quantity}}
					</td>
					<td>
						{{row.unit_price}}
					</td>
					<td>
						{{row.remarks}}
					</td>
				</tr>//-->
	</script>
	<script type="text/template" id="transportPlanningChild1Tpl">
	//<!--
				<tr>
					<td>
						{{row.number}}
					</td>
					<td>
						{{row.goods.name}}
					</td>
					<td>
						{{row.coding}}
					</td>
					<td>
						{{row.specification}}
					</td>
					<td>
						{{row.type}}
					</td>
					<td>
						{{row.gross}}
					</td>
					<td>
						{{row.loadingNumber}}
					</td>
					<td>
						{{row.weight}}
					</td>
					<td>
						{{row.volume}}
					</td>
					<td>
						{{row.depot}}
					</td>
					<td>
						{{row.remarks}}
					</td>
				</tr>//-->
	</script>
